<template>
  <div class="questionInfo">
    <!-- 底部工具栏开始 -->
    <div class="toolBar">
      <div class="o1">
        <div @click="showPublish">
          <i class="iconfont icon-xie"></i>
          写评论
        </div>
      </div>
      <div class="o2" @click="showPublish">
        <i class="iconfont icon-pinglun1"></i>
        {{ questionObj.comm_count }}
      </div>
      <div
        class="o3"
        @click="collectArticle"
        :class="{ active: info.is_collected }"
      >
        <i class="iconfont icon-shoucang3"></i>
        {{ questionObj.collect_count }}
      </div>
      <div class="o4" @click="starArticle">
        <i class="iconfont icon-zan"></i>
        {{ questionObj.like_count }}
      </div>
      <div class="o5" @click="canCelStarArticle">
        <i class="iconfont icon-cha"></i>
        不喜欢
      </div>
    </div>
    <!-- 底部工具栏结束-->
    <!-- 发布评论开始 -->
    <van-popup
      :close-on-click-overlay="false"
      v-model="publishComment"
      @closed="closedPublish"
      position="top"
    >
      <div class="publishBox">
        <van-field
          rows="5"
          type="textarea"
          :autosize="true"
          v-model.trim="publishMessage"
          maxlength="120"
          show-word-limit
          placeholder="请输入评论"
          :border="false"
        />
        <div class="btns">
          <van-button @click="publishCancel">取消</van-button>
          <van-button
            @click="publish"
            :loading="publishSuccess"
            loading-text="发布中"
            loading-type="spinner"
            type="danger"
            >发布评论</van-button
          >
        </div>
      </div>
    </van-popup>
    <!-- 发布评论结束 -->
    <!-- 回复评论开始 -->
    <van-popup
      v-model="showComment"
      :close-on-click-overlay="false"
      position="left"
      @closed="closedReply"
      style="width:80%;height:100%"
    >
      <div class="replyBox">
        <CommentItem
          @starComment="starComment"
          :comment="currentComment"
        ></CommentItem>
        <van-divider />
        <h3>回复({{ subCommemts.length }})</h3>
        <div class="content">
          <template v-for="(item, index) in subCommemts">
            <CommentItem
              @starComment="starComment"
              :key="index"
              :comment="item"
            ></CommentItem>
          </template>
        </div>
        <van-field
          class="text"
          rows="5"
          type="textarea"
          :autosize="true"
          v-model.trim="replyMessage"
          maxlength="120"
          show-word-limit
          placeholder="请输入评论"
          :disabled="replyTextAreaDisabled"
          :center="replyTextAreaDisabled"
        />
        <div class="btns">
          <van-button @click="showComment = false">取消</van-button>
          <van-button
            @click="replyComment"
            :loading="replySuccess"
            loading-text="回复中"
            loading-type="spinner"
            type="danger"
            :disabled="replyBtnDisabled"
            >回复评论</van-button
          >
        </div>
      </div>
    </van-popup>
    <!-- 回复评论结束 -->
    <!-- 头部导航栏开始 -->
    <HmNavBar v-if="scrollTop <= 195">
      <template #rightContent>
        <PopBox
          @reportArticle="reportArticle"
          :reportOption="reportOption"
        ></PopBox>
      </template>
    </HmNavBar>
    <HmNavBar v-else>
      <template #leftContent>
        <van-image round width="32" height="32" :src="info.aut_photo">
          <!-- 加载中loading -->
          <template v-slot:loading>
            <van-loading type="spinner" size="20" />
          </template>
          <!-- 加载失败替换的图片 -->
          <template v-slot:error>
            <img src="@/assets/logo.png" alt="" />
          </template>
        </van-image>
        <div>
          <span style="padding-left:5px">{{ info.aut_name }}</span>
        </div>
      </template>
      <template #rightContent>
        <PopBox
          @reportArticle="reportArticle"
          :reportOption="reportOption"
        ></PopBox>
      </template>
    </HmNavBar>
    <!-- 头部导航栏结束 -->
    <van-skeleton title avatar :row="3" :loading="isDone" />
    <van-skeleton title avatar :row="20" :loading="isDone" />
    <div class="container" v-if="!isDone">
      <div class="header">
        <!-- 头部 -->
        <h3>{{ info.title }}</h3>
        <div class="other">
          <span class="o1">{{ info.pubdate | formatTime }}</span>
          <span class="o2"
            ><i class="iconfont icon-huo"></i>{{ questionObj.like_count }}点赞
          </span>
        </div>
        <!-- 用户信息栏 -->
        <div class="user">
          <div class="left">
            <div class="user-avatar">
              <van-image
                round
                :src="info.aut_photo"
                width="32"
                height="32"
                fit="cover"
                lazy-load
              >
                <!-- 加载中loading -->
                <template v-slot:loading>
                  <van-loading type="spinner" size="20" />
                </template>
                <!-- 加载失败替换的图片 -->
                <template v-slot:error>
                  <img src="@/assets/logo.png" alt="" />
                </template>
              </van-image>
            </div>
            <div class="user-info">
              <div class="username">{{ info.aut_name }}</div>
              <div class="usertype">自媒体</div>
            </div>
          </div>
          <a v-if="!info.is_followed" @click="followAuthor" class="right">
            <i class="iconfont icon-jiahao"></i>
            关注
          </a>
          <a v-else @click="followAuthor" class="right">
            <i class="iconfont icon-icon-test18"></i>
            已关注
          </a>
        </div>
        <van-divider />
      </div>
      <!-- 文章内容 -->
      <div
        :class="{ border: showBorder }"
        @touchstart="move"
        @touchend="endMove"
        class="content"
        v-html="info.content"
      ></div>
      <van-divider />
      <!-- 评论 -->
      <div class="comments" v-if="comments.length">
        <div class="top">
          <h3>
            评论<span>({{ comments.length }})</span>
          </h3>
        </div>
        <div class="list">
          <van-list v-model="loading" :finished="finished" @load="load">
            <template #finished>
              <van-divider>我是有底线的呦~</van-divider>
            </template>
            <template v-for="(item, index) in comments">
              <CommentItem
                @reply="reply"
                @starComment="starComment"
                :key="index"
                :isNotSub="true"
                :comment="item"
              ></CommentItem>
            </template>
          </van-list>
        </div>
      </div>
      <!-- 猜你喜欢 -->
      <div class="otherList">
        <h3><i class="iconfont icon-shu"></i>猜你喜欢</h3>
        <QuestionItem
          v-for="(item, index) in otherList"
          :key="index"
          :question="item"
          :isSearch="false"
        ></QuestionItem>
      </div>
    </div>
    <div class="placeholder"></div>
    <BackTop />
  </div>
</template>

<script>
import {
  articlesArticleId,
  articleComments,
  articleReports,
  comments,
  articleLikingsId,
  articleLikings,
  articleCollections,
  articleCollectionsId,
  commentLikings,
  commentLikingsId,
  userFollowings,
  userFollowingsId,
  articles
} from '@/api/question'
import { mapState } from 'vuex'
export default {
  name: 'QuestionInfo',
  data () {
    return {
      // 文章数据
      info: '',
      // 评论数据
      comments: '',
      // 二楼评论
      subCommemts: '',
      // 当前打开正在看的评论
      currentComment: '',
      // 发布的评论
      publishMessage: '',
      // 文章id
      articleId: this.$route.params.id,
      // 拖动文章内容显示边框
      showBorder: false,
      // 是否显示骨架屏
      isDone: true,
      // 是否加载中转圈
      loading: false,
      // 是否已加载完成
      finished: false,
      // 页容量(后台写死了 只能是10)
      limit: 10,
      // 评论id,相当于数据偏移量,已经查到哪里了,不传默认从第一页开始查,传了从此评论id往后查
      offset: '',
      // 显示回复评论
      showComment: false,
      // 显示发布评论
      publishComment: false,
      // 是否发布成功
      publishSuccess: false,
      // 是否回复成功
      replySuccess: false,
      // 回复评论
      replyMessage: '',
      // 是否禁用回复评论按钮
      replyBtnDisabled: false,
      // 是否禁用回复评论文本域
      replyTextAreaDisabled: false,
      // 猜你喜欢文章集合
      otherList: [],
      // 滚动距离
      scrollTop: 0,
      // 顶部显示的组件
      top: '',
      // 举报类型集合
      reportOption: [
        '标题夸张',
        '低俗色情',
        '错别字多',
        '旧闻重复',
        '广告软文',
        '内容不实',
        '涉嫌违法犯罪',
        '侵权',
        '其他问题'
      ]
    }
  },
  components: {
    PopBox: () => import('@/views/home/question/PopBox'),
    CommentItem: () => import('@/views/home/question/CommentItem'),
    QuestionItem: () => import('@/views/home/question/QuestionItem')
  },
  async created () {
    // 请求数据
    const [article, comm] = await Promise.all([
      this.getArticleInfo(),
      this.getArticleComments()
    ])
    this.info = article.data
    this.isFollowed = this.info.is_collected
    this.comments = comm.data.results
    this.offset = comm.data.last_id
    this.isDone = false
    const res = await articles({
      channel_id: 17,
      timestamp: +new Date(),
      with_top: 1
    })
    this.otherList = res.data.results
  },
  mounted () {
    this.scroll()
  },
  computed: {
    ...mapState(['userInfo', 'questionObj'])
  },
  methods: {
    scroll () {
      window.addEventListener('scroll', () => {
        this.scrollTop =
          document.documentElement.scrollTop ||
          document.body.scrollTop ||
          window.pageYOffset
      })
    },
    // 关注作者
    async followAuthor () {
      // 如果已关注,就取消关注
      if (this.info.is_followed) {
        await userFollowingsId(this.info.aut_id)
        // 更新用户关注信息
        this.info.is_followed = !this.info.is_followed
        return
      }
      // 未关注就关注
      await userFollowings({
        target: this.info.aut_id
      })
      // 更新用户关注信息
      this.info.is_followed = !this.info.is_followed
    },
    // 发布评论框关闭后 清空状态
    closedPublish () {
      this.publishComment = false
      this.publishSuccess = false
      this.publishMessage = ''
    },
    // 点赞评论
    async starComment (comment) {
      console.log(comment)
      // 已点赞就取消点赞
      if (comment.is_liking) {
        await commentLikingsId(comment.com_id.c.join(''))
        comment.is_liking = !comment.is_liking
        comment.like_count !== 0 && comment.like_count--
        return
      }
      // 未点赞就点赞
      await commentLikings({
        target: comment.com_id.c.join('')
      })
      comment.is_liking = !comment.is_liking
      comment.like_count++
    },
    // 收藏文章
    async collectArticle () {
      // 已收藏就取消收藏
      if (this.info.is_collected) {
        await articleCollectionsId(this.articleId)
        this.questionObj.collect_count !== 0 && this.questionObj.collect_count--
        this.info.is_collected = !this.info.is_collected
        this.$toast.success('取消收藏成功')
        return
      }
      // 未收藏就收藏
      await articleCollections({
        target: this.articleId
      })
      this.questionObj.collect_count++
      this.info.is_collected = !this.info.is_collected
      this.$toast.success('收藏成功')
    },
    // 取消点赞文章(不喜欢)
    async canCelStarArticle () {
      await articleLikingsId(this.articleId)
      this.questionObj.like_count !== 0 && this.questionObj.like_count--
      this.$toast.success('取消点赞成功')
    },
    // 取消置空发布框信息
    publishCancel () {
      this.publishComment = false
      this.publishMessage = ''
    },
    // 给文章点赞
    async starArticle () {
      await articleLikings(
        {
          target: this.articleId
        },
        'post'
      )
      this.questionObj.like_count++
      this.$toast.success('点赞成功')
    },
    // 回复评论框关闭时,去掉自己不能回复自己的提示和限制
    closedReply () {
      this.replyTextAreaDisabled = false
      this.replyBtnDisabled = false
      this.replyMessage = ''
    },
    // 回复评论
    async replyComment () {
      // 判空
      if (!this.replyMessage) {
        this.$toast.fail('回复内容不能为空')
        return
      }
      // 修改按钮状态为回复中
      this.replySuccess = true
      // 发请求
      const res = await comments({
        target: this.currentComment.com_id.c.join(''),
        content: this.replyMessage,
        art_id: this.articleId
      })
      // 存储回复的评论
      this.subCommemts.unshift(res.data.new_obj)
      // 清空文本域
      this.replyMessage = ''
      // 修改按钮状态为成功
      this.replySuccess = false
      // 当前评论回复数++
      this.currentComment.reply_count++
    },
    // 发布评论
    async publish () {
      if (!this.publishMessage) {
        this.$toast.fail('评论内容不能为空')
        return
      }
      this.publishSuccess = true
      const res = await comments({
        target: this.articleId,
        content: this.publishMessage
      })
      if (res.status && res.status === 502) {
        this.publishComment = true
        this.publishMessage = ''
        this.publishSuccess = false
        this.$toast.fail('发布失败')
        return
      }
      this.comments.unshift(res.data.new_obj)
      this.publishComment = false
      this.publishMessage = ''
      this.publishSuccess = false
    },
    // 显示发布评论框
    showPublish () {
      this.publishComment = true
    },
    // 显示回复评论框,回显回复列表
    async reply (comment) {
      // 判断是否是自己回复自己,不能自己回复自己
      if (comment.aut_name === this.userInfo.name) {
        this.replyTextAreaDisabled = true
        this.replyBtnDisabled = true
        this.replyMessage = '自己不能回复自己'
      }
      // 存储当前正在回复的评论
      this.currentComment = comment
      // 查询已恢复的评论
      const res = await articleComments({
        type: 'c',
        source: comment.com_id.c.join(''),
        limit: this.limit
      })
      // 存储二楼评论
      this.subCommemts = res.data.results
      // 关闭窗口
      this.showComment = true
    },
    // 下拉加载评论
    async load () {
      const res = await articleComments({
        type: 'a',
        source: this.articleId,
        limit: 10,
        offset: this.offset
      })
      this.comments.push(...res.data.results)
      this.offset = res.data.last_id
      // 如果当前评论总数大于等于库存总数,则加载完成
      if (this.comments.length >= res.data.total_count) {
        this.finished = true
      }
      this.loading = false
    },
    // 举报文章
    async reportArticle (data) {
      const res = await articleReports(data)
      if (res.status !== 409) {
        this.$toast.success('举报成功')
        return
      }
      this.$toast.fail('您已举报过该文章')
    },
    // 拖动文章边框的显隐
    move () {
      this.showBorder = true
    },
    endMove () {
      this.showBorder = false
    },
    // 请求文章详情
    getArticleInfo () {
      return articlesArticleId(this.articleId)
    },
    // 首次加载文章评论
    getArticleComments () {
      return articleComments({
        type: 'a',
        source: this.articleId,
        limit: 10
      })
    }
  }
}
</script>

<style lang="less" scoped>
@import '~@/style/question/questionInfo.less';
</style>
